<?php

namespace Xx2025\Kingdee\Erp\Service;

use Xx2025\Kingdee\Erp\BaseResponse;
use Xx2025\Kingdee\Erp\Client;
use Xx2025\Kingdee\Erp\Response\GyErpTradeAdd;
use Xx2025\Kingdee\Erp\Response\GyErpTradeDeliverysDetailGet;
use Xx2025\Kingdee\Erp\Response\GyErpTradeReturnAdd;
use Xx2025\Kingdee\Erp\Response\GyErpTradeReturnDetailGet;

class Order {

    /**创建发货订单
     * @param string $shopCode  店铺代码
     * @param string $vipCode  会员代码
     * @param string $orderNo  订单号
     * @param string $warehouseCode 仓库代码
     * @param array $detailList  商品明细列表 [['item_code'=>'001','sku_code'=>'001','price'=>'1.0','qty'=>1]]
     * @param string $receiverName  收件人
     * @param string $receiverMobile 收件人手机
     * @param string $province 省
     * @param string $city 市
     * @param string $district 区
     * @param string $detail  详细地址
     * @param array $extraParams  额外参数
     * @return GyErpTradeAdd
     * @throws \Throwable
     */
    public static function newShippingOrder(
        string $shopCode,
        string $vipCode,
        string $orderNo,
        string $warehouseCode,
        array $detailList,
        string $receiverName,
        string $receiverMobile,
        string $province,
        string $city,
        string $district,
        string $detail,
        array $extraParams = [],
    ) :GyErpTradeAdd
    {

        $requestParams = [
            'shop_code'=>$shopCode,
            'vip_code'=>$vipCode,
            'platform_code'=>$orderNo,
            'warehouse_code'=>$warehouseCode,
            'deal_datetime'=>date('Y-m-d H:i:s'),
            'order_type_code'=>'Sales',
            'details'=>$detailList,
            'receiver_name'=>$receiverName,
            'receiver_mobile'=>$receiverMobile,
            'receiver_province'=>$province,
            'receiver_city'=>$city,
            'receiver_district'=>$district,
            'receiver_address'=>$detail,
        ];

        foreach ($extraParams as $key => $value) {
            $requestParams[$key] = $value;
        }

        $response = Client::request('gy.erp.trade.add', $requestParams, GyErpTradeAdd::getInstance());

        $response->setBillCode($response->getResponseContents()['code'] ?? '');
        return $response;
    }


    /**发货单物流信息
     * @param string $orderNo
     * @return GyErpTradeDeliverysDetailGet
     * @throws \Throwable
     */
    public static function getLogisticsInfo(string $orderNo) :GyErpTradeDeliverysDetailGet
    {



        $params = [
            'outer_code'=>$orderNo,
        ];
        $res = Client::request('gy.erp.trade.deliverys.get', $params);


        if(!$res->isSuccessful()) {
            return GyErpTradeDeliverysDetailGet::getInstance();
        }



        $billCode = $res->getResponseContents()['deliverys'][0]['code'] ?? '';

        if($billCode){
            $detailParams = [
                'code'=>$billCode,
            ];
            $response = Client::request('gy.erp.trade.deliverys.detail.get', $detailParams, GyErpTradeDeliverysDetailGet::getInstance());
        }else{
            //查询历史发货详情

            $params = [
                'platform_code'=>$orderNo,
            ];
            $res = Client::request('gy.erp.trade.history.get', $params);

            if(!$res->isSuccessful()) return GyErpTradeDeliverysDetailGet::getInstance();


            $billCode = $res->getResponseContents()['orders'][0]['code'] ?? '';
            if(!$billCode)  return GyErpTradeDeliverysDetailGet::getInstance();

            $detailParams = [
                'code'=>$billCode,
            ];
            $response = Client::request('gy.erp.trade.deliverys.detail.history.get', $detailParams, GyErpTradeDeliverysDetailGet::getInstance());
        }


        $deliveryState = $response->getResponseContents()['delivery']['delivery_statusInfo']['delivery'] ?? 0;
        if($deliveryState != 2){
            //未发货
            $response->setDeliveryState(false);
            return $response;
        }

        $uniqueCodeList = [];
        $response->setDeliveryState(true);
        $responseArr = $response->getResponseContents();
        $details = $responseArr['delivery']['details'] ?? [];
        foreach ($details as $item){
            $platOrderNo = $item['platform_code'] ?? '';
            if($platOrderNo == $orderNo){
                $detailUniqueArr = $item['detail_unique'] ?? [];
                foreach ($detailUniqueArr as $v){
                    $uniqueCodeList[] = $v['unique_code'];
                }
            }
        }
        $response->setExpressNo($responseArr['delivery']['express_no'] ?? '');
        $response->setExpressName($responseArr['delivery']['express_name'] ?? '');
        $response->setDeliveryAt($responseArr['delivery']['delivery_statusInfo']['delivery_date'] ?? '');
        $response->setErpBillCode($responseArr['delivery']['code'] ?? '');
        $response->setUniqueCodeList($uniqueCodeList);


        return $response;
    }


    /**订单退货  apiUrl：https://vip.kingdee.com/knowledge?productLineId=3&productId=28&domain=API&lang=zh-CN
     * @param string $shopCode  //店铺代码
     * @param string $vipCode  会员代码
     * @param string $tradePlatformCode  销售订单平台单号
     * @param string $typeCode 退货原因代码
     * @param string $expressName 退回快递名称
     * @param string $expressNo 退回运单号
     * @param string $warehouseCode  退回仓库代码
     * @param array $itemDetail  退入商品明细， 示例：[['item_code'=>'商品代码','sku_code'=>'sku代码','qty'=>1,'unique_code'=>'唯一码','platform_code'=>'发货订单号']]
     * @return GyErpTradeReturnAdd
     * @throws \Throwable
     */
    public static function newOrderReturn(
        string $shopCode,
        string $vipCode,
        string $tradePlatformCode,
        string $typeCode,
        string $expressName,
        string $expressNo,
        string $warehouseCode,
        array $itemDetail,
        array $extraParams = [],
    ) :GyErpTradeReturnAdd
    {
        $requestParams = [
            'shop_code'=>$shopCode,
            'vip_code'=>$vipCode,
            'trade_platform_code'=>$tradePlatformCode,
            'return_type'=>1,
            'type_code'=>$typeCode,
            'express_name'=>$expressName,
            'express_num'=>$expressNo,
            'warehousein_code'=>$warehouseCode,
            'item_detail'=>$itemDetail,
        ];
        foreach ($extraParams as $key => $value) {
            $requestParams[$key] = $value;
        }

        $response = GyErpTradeReturnAdd::getInstance();
        Client::request('gy.erp.trade.return.add', $requestParams, $response);

        if($response->isSuccessful()){
            $response->setBillCode($response->getResponseContents()['code']);
        }

        return $response;

    }


    /**退货查询 apiUrl：https://vip.kingdee.com/knowledge/309018233921535232?productLineId=3&isKnowledge=2&lang=zh-CN
     * @param string $billCode
     * @return GyErpTradeReturnDetailGet
     * @throws \Throwable
     */
    public static function queryOrderReturn(string $billCode) :GyErpTradeReturnDetailGet
    {
        $requestParams = [
            'code'=>$billCode,
        ];
        $response = GyErpTradeReturnDetailGet::getInstance();
        Client::request('gy.erp.trade.return.detail.get', $requestParams, $response);

        $resData = $response->getResponseContents();

        if(isset($resData['tradeReturn']['receive']) && $resData['tradeReturn']['receive'] == 1){
            $receiveAt = $res['tradeReturn']['receive_date'] ?? '';
            $response->setReturnState(1);
            $response->setErpReceiveDate($receiveAt);
            return $response;
        }

        if(isset($resData['tradeReturn']['cancel']) && $resData['tradeReturn']['cancel'] == true){

            $response->setReturnState(-1);
        }
        return $response;
    }

    /**取消发货订单  apiUrl：https://vip.kingdee.com/knowledge/346956209099823872?productLineId=3&isKnowledge=2&lang=zh-CN
     * @param string $billCode
     * @return BaseResponse
     * @throws \Throwable
     */
    public static function cancelOrder(string $billCode) :BaseResponse
    {

        if(str_starts_with($billCode, 'SDO')){
            $billCode = mb_substr($billCode, 3, null, 'UTF-8');
        }

        $requestParams = [
            'ids'=>[$billCode],
        ];
        $response = Client::request('gy.erp.trade.order.canceldeliveryorder', $requestParams);
        return $response;
    }

}